package com.lh.service.impl;

import com.lh.domian.ResponseResults;
import com.lh.domian.entity.LoginUser;
import com.lh.domian.entity.User;
import com.lh.domian.vo.UserInfoVo;
import com.lh.domian.vo.UserLoginVo;
import com.lh.exception.MyException;
import com.lh.service.LoginService;
import com.lh.utils.BeanCopyUtils;
import com.lh.utils.JwtUtil;
import com.lh.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Author LuoHang
 * @Date 2022-08-26 22:26
 **/
@Service("loginService")
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResults login(User user)  {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //判断认证是否通过
        if (Objects.isNull(authenticate)){
            throw new MyException("用户名或密码错误");
        }
        //获取userId 生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Long userId = loginUser.getUser().getId();
        //将userId 通过工具类生成JWT
        String jwt = JwtUtil.createJWT(userId.toString());
        //把用户信息存储到redis
        redisCache.setCacheObject("bloglogin:"+jwt,loginUser);
        //将user转换为userInfoVo
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        UserLoginVo userLoginVo = new UserLoginVo(jwt,userInfoVo);
        //把token和userInfo 封装返回
        return new ResponseResults(200,userLoginVo);
    }
}
